package org.xs.web.http;

import java.io.Serializable;
import java.util.List;

public class Identity {
	
	private static String Key ="identity.key";
	
	public static boolean login(String username){
		return login(new User(username));
	}
	
	private static boolean login(User user){
		if(S.session() == null) return false;
		S.session().set(Key, user);
		return true;
	}
	
	public static boolean login(String username,String password){
		return login(new User(username,password));
	}
	
	public static boolean login(String username,Long userId){
		return login(new User(username,userId));
	}
	
	public static boolean login(String username,Object user){
		return login(new User(username,user));
	}
	
	public static boolean isLogined(){
		if(S.session() == null) return false;
		return S.session().get(Key) != null ? true : false;
	}
	
	public static User getLogined(){
		return (User) (isLogined() ? S.session().get(Key) : null);
	}
	
	public static String username(){
		if(isLogined()){
			return getLogined().username;
		}
		return "";
	}
	
	public static boolean logout(){
		if(S.session() == null) return true;
		S.session().remove(Key);
		S.session().invalidate();
		return true;
	}
	
	public static Long[] roles(){
		if(isLogined()){
			User user= getLogined();
			if(user.delegate != null){
				return user.roles;
			}
			return new Long[]{};
		}
		return new Long[]{};
	}
	
	public static Long[] auths(){
		if(isLogined()){
			User user= getLogined();
			if(user.delegate != null){
				return user.auths;
			}
			return new Long[]{};
		}
		return new Long[]{};
	}
	
	public static boolean isAdmin(){
		if(isLogined()){
			User user= getLogined();
			if(user.delegate != null){
				return user.isAdmin;
			}
		}
		return false;
	}
 
	
}

class User implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	public Object delegate;
	public String username;
	public Long userId;
	public String password;
	public Long[] roles;
	public String[] roleNames;
	public Long[] auths;
	public boolean isAdmin;
	
	public User(String username){
		this.username = username;
	}
	
	public User(String username,String password){
		this.username = username;
		this.password = password;
	}
	public User(String username,String password,Long userid){
		this.username = username;
		this.password = password;
		this.userId = userid;
	}
	public User(String username,Long userid){
		this.username = username;
		this.userId = userid;
	}
	public User(String username,Object user){
		this.username = username;
		this.delegate = user;
	 
		 
	}
}

